package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Host;

public class HostConfigManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;

	public HostConfigManage(DBConn db)
	{
		this.db=db;
	}
	public HostConfigManage(DBPool dbpool)
	{
		this.dbpool=dbpool;
	}
	
	public Host getData(int HostID)
	{
		Host host = new Host();
		String sql="select * from Host_Config where HostID="+HostID;
		try 
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			if(rs.next())
			{
				host.setName(rs.getString("HostName"));
				host.setIP(rs.getString("HostIP"));
				host.setReportedTime(rs.getString("Reported"));
				host.setLocation(rs.getString("Location"));
				host.setGmond_started(rs.getString("gmond_started"));
			}
			rs.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
		
		return host;
	}

	public String addRecord(int HostID,Host host)
	{
		String hostName=host.getName();
		String hostIP=host.getIP();
		String reported=host.getReportedTime();
		String location=host.getLocation();
		String gmond_started=host.getGmond_started();
		
		String sql="insert into Host_Config (HostID,HostName,HostIP,Reported,Location,GMOND_STARTED) values ("+HostID+",'"+hostName+"','"+hostIP+"','"+reported+"','"+location+"','"+gmond_started+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(int HostID)
	{
		String sql="delete from host_Config where HostID="+HostID ;
		try
		{
			stat=dbpool.connect();
			stat.execute(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(String HostName)
	{
		String sql="delete from Host_Config where HostName='"+HostName+"'";
		try
		{
			stat=dbpool.connect();
			stat.execute(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
